package com.study.pdfUtil;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class ItextEditPDF {

	public void exportPdf() throws DocumentException, IOException {// 利用模板生成pdf
		// 模板路径
		String templatePath = "C:/TestCreatePDF/demo_table.pdf";
		// 生成的新文件路径
		String newPDFPath = "C:/TestCreatePDF/newPdf.pdf";
		PdfReader reader;
		FileOutputStream out;
		ByteArrayOutputStream bos;
		PdfStamper stamper;
		BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		try {
			out = new FileOutputStream(newPDFPath);// 输出流
			reader = new PdfReader(templatePath);// 读取pdf模板
			bos = new ByteArrayOutputStream();
			stamper = new PdfStamper(reader, bos);
			AcroFields form = stamper.getAcroFields();

			String[] str = { "我是一个中国人121asdas", "我是一个中国人", "我是一个中国人", "1994-00-00" };
			int i = 0;
			java.util.Iterator<String> it = form.getFields().keySet().iterator();
			while (it.hasNext()) {
				String name = it.next().toString();
				System.out.println(name);
				// 设置支持中文
				form.setFieldProperty(name, "textfont", baseFont, null);
				form.setField(name, str[i++]);
			}
			stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
			stamper.close();

			Document doc = new Document();
			PdfCopy copy = new PdfCopy(doc, out);
			doc.open();
			int pageCount = new PdfReader(bos.toByteArray()).getNumberOfPages();
			System.out.println("pageCount = " + pageCount);
			for (int pageNum = 1; pageNum <= pageCount; pageNum++) {
				// 每一页都Copy
				PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), pageNum);
				copy.addPage(importPage);
			}

			doc.close();

		} catch (IOException e) {
			System.out.println("IOException" + e);
		} catch (DocumentException e) {
			System.out.println("DocumentException" + e);
		}

	}

	public static void main(String[] args) throws DocumentException, IOException {
		new ItextEditPDF().exportPdf();
	}
}
